package com.pkutech.carcasher.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import com.dd.processbutton.iml.ActionProcessButton;
import com.pkutech.carcasher.R;
import com.pkutech.carcasher.bean.LoginResponse;
import com.pkutech.carcasher.db.RealmManager;
import com.pkutech.carcasher.network.SoapApi;
import com.pkutech.carcasher.utils.Md5;
import com.pkutech.carcasher.utils.ToastUtil;
import com.rengwuxian.materialedittext.MaterialEditText;

import java.util.HashSet;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * 登陆
 * Created by cyy on 2016/6/5.
 */
public class UserLoginActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.pwdEditText)
    MaterialEditText pwdEditText;
    @BindView(R.id.pwdCheckBox)
    CheckBox pwdCheckBox;
    @BindView(R.id.loginBtn)
    ActionProcessButton loginBtn;
    @BindView(R.id.userNameEditText)
    MaterialEditText userNameEditText;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_login);
        ButterKnife.bind(this);
        pwdCheckBox = (CheckBox) findViewById(R.id.pwdCheckBox);
        pwdCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // 设置EditText的密码为可见的
                    pwdEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    pwdEditText.setSelection(pwdEditText.getText().toString().length());
                } else {
                    // 设置密码为隐藏的
                    pwdEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    pwdEditText.setSelection(pwdEditText.getText().toString().length());
                }
            }
        });
    }

    @OnClick(R.id.loginBtn)
    public void login() {
        if(TextUtils.isEmpty(userNameEditText.getText().toString())){
            ToastUtil.showInfoToast(this, "请输入用户名", ToastUtil.Position.TOP);
            return;
        }
        if(TextUtils.isEmpty(pwdEditText.getText().toString())){
            ToastUtil.showInfoToast(this, "请输入密码", ToastUtil.Position.TOP);
            return;
        }
//        SoapApi.login(userNameEditText.getText().toString(), Md5.getMD5(pwdEditText.getText().toString()))
        SoapApi.login(userNameEditText.getText().toString(), pwdEditText.getText().toString())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        loginBtn.setProgress(1);
                    }
                })
                .subscribe(new Subscriber<LoginResponse>() {
                    @Override
                    public void onCompleted() {
                        loginBtn.setProgress(0);
                    }

                    @Override
                    public void onError(Throwable e) {
                        loginBtn.setProgress(0);
                        ToastUtil.showInfoToast(UserLoginActivity.this, "登陆失败", ToastUtil.Position.TOP);
                    }

                    @Override
                    public void onNext(LoginResponse loginResponse) {
                        loginBtn.setProgress(0);
                        RealmManager.clearUserInfo();
                        if (loginResponse != null && !TextUtils.isEmpty(loginResponse.getStatus()) && "true".equals(loginResponse.getStatus())) {
                            loginFlag=0;
                            ToastUtil.showSuccessToast(UserLoginActivity.this, "登陆成功", ToastUtil.Position.TOP);
                            if(loginResponse.getData() != null && loginResponse.getData().size() > 0){
                                RealmManager.saveUserInfo(loginResponse.getData().get(0));
                                Set<String> tags = new HashSet<String>();
                                tags.add(loginResponse.getData().get(0).getRoadid());
                                JPushInterface.setTags(UserLoginActivity.this, tags, new TagAliasCallback() {
                                    @Override
                                    public void gotResult(int i, String s, Set<String> set) {
                                        if (i == 0) {
                                            Log.d("JPush", "Tags设置成功");
                                        }
                                    }
                                });
                                JPushInterface.setAlias(UserLoginActivity.this, loginResponse.getData().get(0).getId(), new TagAliasCallback() {
                                    @Override
                                    public void gotResult(int i, String s, Set<String> set) {
                                        if (i == 0) {
                                            Log.d("JPush", "Alias设置成功");
                                        }
                                    }
                                });
                            }
                            Intent intent = new Intent(UserLoginActivity.this, HomeActivity.class);
                            startActivity(intent);
                            finish();
                        } else {
                            if(loginResponse != null && !TextUtils.isEmpty(loginResponse.getMessage())){
                                ToastUtil.showInfoToast(UserLoginActivity.this, loginResponse.getMessage(), ToastUtil.Position.TOP);
                            }else{
                                ToastUtil.showInfoToast(UserLoginActivity.this, "登陆失败", ToastUtil.Position.TOP);
                            }
                        }
                    }
                });
    }

//    @OnClick(R.id.register)
//    public void regist(View view) {
//        Intent intent = new Intent(this, RegisterActivity.class);
//        startActivity(intent);
//    }

}
